package controller;

import java.util.ArrayList;
import java.util.List;

import javax.swing.JDialog;
import javax.swing.JOptionPane;

import main.model.Diagram;
import main.model.Entity;
import main.model.Hierarchy;
import main.model.Relation;
import view.SelectGlobalEntityView;
import controller.editor.EditorController;

public class SelectGlobalEntityController extends Controller{

	private EditorController controller;
	private SelectGlobalEntityView view;

	public SelectGlobalEntityController(EditorController c){
		this.controller = c;
	}

	@Override
	public void displayView() {
		ArrayList<String> s = new ArrayList<String>();
		Diagram diagram = controller.getProject().getDiagramByName("Principal");
		s.addAll(diagram.getOwnEntitiesNames());
		view = new SelectGlobalEntityView(s);
		view.setController(this);
		view.show();
	}

	public void handleButtonTerminar(){
		String selectedEntity = view.getSelectedEntity();
		if (selectedEntity != null){
			if (this.controller.getCurrentDiagram().getEntityByName(selectedEntity) == null){
				Entity e = this.controller.getProject().getEntityInProjectByName(selectedEntity);
				JDialog dialogo = new JDialog(); 
				JOptionPane.showMessageDialog(dialogo,"Se ha Seleccionado a la entidad: " + selectedEntity, "Notificacion",
						JOptionPane.INFORMATION_MESSAGE);	
				this.controller.getCurrentDiagram().addEntity(e);
				Diagram parentDiagram = this.controller.getProject().getDiagramByName(e.getDiagramParent());
				List<Relation> relatedRelations = this.controller.getCurrentDiagram().getExistingRelations(parentDiagram.getRelationsFromEntity(e));
				if (!relatedRelations.isEmpty()){
					for (Relation rel : relatedRelations) {
						this.controller.getCurrentDiagram().addRelation(rel);
					}
				}
				List<Hierarchy> relatedHierarchies = this.controller.getCurrentDiagram().getExistingHierarchies(parentDiagram.getHierarchiesFromEntity(e));
				if (!relatedHierarchies.isEmpty()){
					for (Hierarchy h : relatedHierarchies) {
						this.controller.getCurrentDiagram().addHierarchy(h);
					}
				}
				this.controller.notifyNewGlobalEntity(e, relatedRelations, relatedHierarchies);
			} else {
				JDialog dialogo = new JDialog(); 
				JOptionPane.showMessageDialog(dialogo,"Ya hay una entidad con ese nombre", "Notificacion",
						JOptionPane.INFORMATION_MESSAGE);	
			}
		}
		view.hide();
	}

}
